<?php
/**
 * Controller is the customized base controller class.
 * All controller classes for this application should extend from this base class.
 */
class Controller extends CController {

    /**
     * @var string the default layout for the controller view. Defaults to 'column1',
     * meaning using a single column layout. See 'protected/views/layouts/column1.php'.
     */
    //public $layout = '//../views/layouts/column2';
    public $layout = '//../views/layouts/1column';

    /**
     * @var array context menu items. This property will be assigned to {@link CMenu::items}.
     */
    public $menu = array();

    /**
     * @var array the breadcrumbs of the current page. The value of this property will
     * be assigned to {@link CBreadcrumbs::links}. Please refer to {@link CBreadcrumbs::links}
     * for more details on how to specify this property.
     */
    public $breadcrumbs = array();

    /**
     * @var string UI images path.
     */
    public $imagesPath;

    /**
     * @var string UI css path.
     */
    public $cssPath;

    /**
     * @var string UI js path.
     */
    public $jsPath;

    /**
     * @var string Current currency symbol
     */
    public $currency;

    /**
     * @var string Current country code
     */
    public $countryCode;

    /**
     * @var string site language
     */
    public $language='en';
    
    /**
     * @var boolean is debug mode
     */
    public $debugMode = false;

    /**
     * @var boolean is maintenance mode
     */
    public $maintenanceMode = false;

    /*
     * @var captcha mode
     */
    public $captchaMode; // value: default, math, mathverbal, logical, words

    /**
     * @var string current working form id
     */
    public $formId = 'form-id';

    /**
     * @var array meta description
     */
    public $metaTags;

    public $formMessage;
    
    
    /**
     * @var string logout url
     */
    public $logoutUrl;
    public $contactUsUrl;
    public $termsOfUseUrl;
    public $disclaimersUrl;
    public $privacyUrl;
    
    /**
     * email config
     */
    public $domainName;
    public $domainNameUrl;
    public $edmImagesPath;
    public $edmUrl;
    public $edmSubject;
    
    /**
     *  
     */
    public function init() {
        
        if(isset(Yii::app()->session['visitor_country'])){
            $this->countryCode=Yii::app()->session['visitor_country'];
        }else{
            $this->countryCode=Yii::app()->session['visitor_country']=Environment::isProduction() ? 
                Yii::app()->geoip->lookupCountryCode(Yii::app()->request->userHostAddress) : Yii::app()->params['defaultCountryCode'];
        }
        
        if(Yii::app()->user->isGuest){
            $defaultLanguage=in_array($this->countryCode, array('CN','HK','MN','MO','TW'))? 'zh_cn':Yii::app()->params['defaultLanguage'];
        }else
            $defaultLanguage=Yii::app()->user->preferredLanguageCode;
        
        Yii::import('ext.widgets.LanguageSelectorPortlet');
        LanguageSelectorPortlet::setLanguage(Option::language(), $defaultLanguage);
        $this->language=Yii::app()->language;
        
        parent::init();
        
        $this->imagesPath = Yii::app()->theme->baseUrl . '/img';
        $this->cssPath = Yii::app()->theme->baseUrl . '/css';
        $this->jsPath = Yii::app()->theme->baseUrl . '/js';
        
        Yii::setPathOfAlias('componentsViewPath', 'themes/' . Yii::app()->theme->name . '/views/widgets');
        $this->maintenanceMode = Yii::app()->params['maintenanceMode'];
        $this->debugMode = Yii::app()->params['debugMode'];
        $this->currency = Yii::app()->params['defaultCurrency'];
        $this->captchaMode = isset(Yii::app()->params['captchaMode'])? Yii::app()->params['captchaMode']:null;
        
        // global url
        if(!Yii::app()->user->isGuest){
            $this->logoutUrl = Yii::app()->user->isSocialUser?
                $this->url('user/social/logout', array('token' => Yii::app()->request->csrfToken)):
                $this->url('user/auth/logout', array('token' => Yii::app()->request->csrfToken));
        }
        $this->contactUsUrl=$this->url('site/contact');
        $this->termsOfUseUrl=$this->url('site/termsofuse');
        $this->disclaimersUrl=$this->url('site/disclaimers');
        $this->privacyUrl=$this->url('site/privacy');
        
        $this->pageTitle=CHtml::encode(Yii::app()->params['title']);
        //echo Yii::getVersion();
    }//end function

    public function filters() {
        return array(
            'accessControl',
            array(
                'application.filters.html.ECompressHtmlFilter',
                'gzip' => (YII_DEBUG ? false : true),
                'doStripNewlines' => (YII_DEBUG ? false : true),
                'actions' => '*'
            ),
        );
    }

    /*
    public function filterAccessControl($filterChain) {
        $rules = $this->accessRules();

        //$rules[] = array('deny'); // default deny
        //$rules[]=array('deniedCallback'=>'redirectToActionNotAllow');
        
        $filter = new CAccessControlFilter;
        $filter->setRules($rules);
        $filter->filter($filterChain);
    }
    
    public function redirectToActionNotAllow($user, $rule){
        $this->redirect('/site/blockedaction');
    }*/
    
    protected function beforeAction($action) {
        if ($this->maintenanceMode && strtolower($action->id) !== 'maintenance')
            $this->redirect(Yii::app()->createUrl('site/maintenance'));
        
        /*
          $_uri = false;
          if (Yii::app()->urlManager->showScriptName == false){
          if (strpos(Yii::app()->request->requestUri, '/index.php') !== false){
          $_uri = str_replace("/index.php", "", Yii::app()->request->requestUri);
          }
          if (Yii::app()->controller->action->id == 'index'){
          if (!$_uri) {
          if (strpos(Yii::app()->request->requestUri, "/index") !== false){
          $_uri = str_replace("/index", "", Yii::app()->request->requestUri);
          }
          } else {
          if (strpos($_uri, "/index") !== false){
          $_uri = str_replace("/index", "", $_uri);
          }
          }
          }
          }

          if ($_uri !== false){
          $this->redirect($_uri);
          }
         */

        return parent::beforeAction($action);
    }

    protected function beforeRender($view) {
        if (parent::beforeRender($view)) {
            $this->breadcrumbs=  array_unique(array_filter($this->breadcrumbs));
        }//end if	    
        return true;
    }
    
    protected function afterRender($view, &$output){
        $this->generateMetaTags();
    }
    
    public function initEmail(){
        Yii::setPathOfAlias('edmViewPath', 'themes/' . Yii::app()->params['theme'] . '/views/edm');
        $this->domainName=Yii::app()->request->hostInfo;
        $this->domainNameUrl=Yii::app()->request->hostInfo . Yii::app()->request->baseUrl;
        $this->edmImagesPath=$this->domainNameUrl . '/themes/' . Yii::app()->params['theme'] . '/images/edm';
    }
    
    public function loginRequired($url=null){
        if(Yii::app()->user->isGuest){
            Yii::app()->user->loginRequired();
            if(!empty($url)) Yii::app()->session['urlReferrer']=$url;
        }
    }

    public function loginToUrlReferrer(){
        if(isset(Yii::app()->session['urlReferrer'])){
            $url=Yii::app()->session['urlReferrer'];
            unset(Yii::app()->session['urlReferrer']);
            Yii::app()->request->redirect($url);
        }
    }
    
    public function generateMetaTags() {
        if(!empty($this->metaTags)) $this->metaTags=array_filter($this->metaTags);
        if (empty($this->metaTags)) {
            Yii::app()->clientScript
                    ->registerMetaTag(Yii::app()->params['defaultMetaDescription'], 'description')
                    ->registerMetaTag(Yii::app()->params['defaultMetaKeywords'], 'keywords')
            ;
        } else {
            foreach ($this->metaTags as $name => $content)
                Yii::app()->clientScript->registerMetaTag($content, $name);
        }
    }//end function

    protected function performAjaxValidation() {
        if (isset($_POST['ajax']) && $_POST['ajax'] === $this->formId) {
            $response='';
            foreach(func_get_args() as $model){
                $response .= CActiveForm::validate($model);
            }
            return $response;
            Yii::app()->end();
        }
    }//end function

    public function setFlash($type, $message) {
        Yii::app()->user->setFlash($type, $message);
    }//end function
    
    public function getFlashes($htmlOptions=array(), $tag='div'){
        foreach (Yii::app()->user->getFlashes() as $key => $message) {
            if(isset($htmlOptions['class'])) $htmlOptions['class']=str_replace('{status}',$key, $htmlOptions['class']);
            echo CHtml::openTag($tag, $htmlOptions)
            . $message
            . CHtml::closeTag($tag);
            echo "\n";
        }//end foreach loop
    }
    
    public function urlFormat($value){
        return Helper::url_slug($value);
    }
    
    /**
     * menu function
     * @return type
     */
    public function topMenu(){
        if (Yii::app()->user->isGuest) {
            return array(
                array('label' => Lang::t('top.menu.register'), 'url' => $this->url('user/auth/register'), 'itemOptions' => array('class' => 'register')),
                array('label' => Lang::t('top.menu.login'), 'url' => $this->url('user/auth/login'), 'itemOptions' => array('class' => 'login')),
                //array('label' => Lang::t('top.menu.merchant.login'), 'url' => $this->url('merchant/auth/login'), 'itemOptions' => array('class' => 'merchant-login')),
            );
        } else {
            return array(
            	array('label' => Lang::t('top.menu.topic'), 'url'=>$this->url('topic')),
                array('label' => Yii::app()->user->displayName, 'url'=>$this->url('user/profile/update')),
                //array('label' => Lang::t('top.menu.office.dashboard'), 'url' => $this->url('acp/site/index'), 'visible' => Yii::app()->user->isAdmin, 'itemOptions' => array('class' => 'my-office')),
                //array('label' => Lang::t('top.menu.my.dashboard'), 'url' => Yii::app()->user->returnUrl, 'itemOptions' => array('class' => 'my-page')),
                //array('label' => Lang::t('top.menu.my.page'), 'url' => Yii::app()->user->url, 'itemOptions' => array('class' => 'my-page')),
                //array('label' => Lang::t('top.menu.my.account.page'), 'url' => Yii::app()->user->accountUrl, 'visible'=>Yii::app()->user->isMerchant, 'itemOptions' => array('class' => 'my-account-page')),
                //array('label' => Lang::t('top.menu.my.shortlist'), 'url' => $this->url('user/shortlist/index'), 'active'=>$this->isMenuActive('user/shortlist/index'), 'itemOptions' => array('class' => 'my-shortlist')),
                //array('label' => Lang::t('top.menu.my.account'), 'url' => $this->url('account/profile/update'), 'active'=>$this->isMenuActive('account/profile/update'), 'visible' => Yii::app()->user->hasAccount, 'itemOptions' => array('class' => 'my-account')),
                array('label' => Lang::t('top.menu.my.profile'), 'url' => $this->url('user/profile/update'), 'active'=>$this->isMenuActive('user/profile/update'), 'itemOptions' => array('class' => 'my-profile')),
                array('label' => Lang::t('top.menu.change.password'), 'url' => $this->url('user/profile/password'), 'active'=>$this->isMenuActive('user/profile/password'), 'itemOptions' => array('class' => 'my-password')),
                //array('label' => Lang::t('top.menu.settings'), 'url' => $this->url('user/profile/settings'),'active'=>$this->isMenuActive('user/profile/settings'), 'itemOptions' => array('class' => 'my-settings')),
                //array('itemOptions'=>array('class'=>'divider')),
                array('label' => Lang::t('top.menu.logout'), 'url' => $this->logoutUrl, 'itemOptions' => array('class' => 'my-logout')),
            );
        }//end if else
    }
        
    private function menu(&$pages, &$htmlOptions, $parent=0){
        $userRole = Yii::app()->user->isGuest ? Option::USER_ROLE_GUEST : Yii::app()->user->roleCode;
        $menu=array();
        foreach($pages as $id=>$data){
            if(in_array($userRole, $data['user_access']) && $data['parent']==$parent){
                $url=$data['type'] == Option::ARTICLE_TYPE_URL || !empty($data['external_url']) ? $data['external_url'] : $data['url'];
                $menu[$data['position']] = array(
                        'label' => $data['title'],
                        'url' => $url,
                        'active' => $this->isPageActive($url),
                        'itemOptions' => array(
                            'class' => $data['button_css_class'],
                        ),
                        'items'=>$this->menu($pages, $htmlOptions, $id),
                    );
                
                if($menu[$data['position']]['items']){
                    $menu[$data['position']]['itemOptions']=$htmlOptions['parentItemOptions'];
                    if($parent){
                        $menu[$data['position']]['itemOptions']['class'] = isset($htmlOptions['parentItemOptions']['class'])? implode(' ', array(
                            'dropdown-submenu',
                            $data['button_css_class'],
                        )):$data['button_css_class'];
                    }else{
                        $menu[$data['position']]['itemOptions']['class'] = isset($htmlOptions['parentItemOptions']['class'])? implode(' ', array(
                            $menu[$data['position']]['itemOptions']['class'],
                            $data['button_css_class'],
                        )):$data['button_css_class'];
                        $menu[$data['position']]['label']=$data['title'].$htmlOptions['parentCaret'];
                    }
                    $menu[$data['position']]['linkOptions']=$htmlOptions['parentLinkOptions'];
                }
                $menu[$data['position']]['linkOptions']['target']=$data['is_new_window'] ? '_blank' : '_parent';
            }       
        }
        ksort($menu);
        return $menu;
    }
    
    public function navigationMenu($htmlOptions=array()){
        $pages=Article::model()->getMenu(Option::SECTION_NAVIGATION_MENU);
        $menu=array();
        if(!$pages) return $menu;        
        return $this->menu($pages, $htmlOptions);

        return array(
            array('label' => Lang::t('navigation.menu.home'), 'url' => Yii::app()->homeUrl,'active'=>$this->isMenuActive('site/index'), 'itemOptions'=>array('class'=>'home')),
            //array('label' => Lang::t('navigation.menu.promotion'), 'url' => $this->url('promotion/index'), 'active'=>$this->isMenuActive('promotion/index'), 'itemOptions'=>array('class'=>'promotion')),
            array('label' => Lang::t('navigation.menu.news'), 'url' => $this->url('news'),'active'=>$this->isMenuActive('news/listing'), 'itemOptions'=>array('class'=>'news')),
            array('label' => Lang::t('navigation.menu.about'), 'url' => $this->url('site/about'), 'active'=>$this->isMenuActive('site/about'), 'itemOptions'=>array('class'=>'about')),
            array('label' => Lang::t('navigation.menu.contact'), 'url' => $this->url('site/contact'),'active'=>$this->isMenuActive('site/contact'), 'itemOptions'=>array('class'=>'contact-us')),
            //array('label' => Lang::t('navigation.menu.sitemap'), 'url' => $this->url('site/sitemap'),'active'=>$this->isMenuActive('site/sitemap'), 'itemOptions'=>array('class'=>'sitemap')),
        );
    }
    
    public function footerMenu($htmlOptions=array()){
        
    	/*
    	$pages=Article::model()->getMenu(Option::SECTION_FOOTER);
        $menu=array();
        if(!$pages) return $menu;        
        return $this->menu($pages, $htmlOptions);
        */
        return array(
            array('label' => Lang::t('footer.menu.privacy.policy'), 'url' => $this->privacyUrl, 'itemOptions'=>array('class'=>'privacy-policy')),
            array('label' => Lang::t('footer.menu.disclaimers'), 'url' => $this->disclaimersUrl, 'itemOptions'=>array('class'=>'disclaimers')),
            array('label' => Lang::t('footer.menu.terms.of.use'), 'url' => $this->termsOfUseUrl, 'itemOptions'=>array('class'=>'terms-of-use')),
        );
    }
    
    public function footerMenu1($htmlOptions=array()){
        $pages=Article::model()->getMenu(Option::SECTION_FOOTER_MENU_1);
        $menu=array();
        if(!$pages) return $menu;        
        return $this->menu($pages, $htmlOptions);
    }
    
    public function footerMenu2($htmlOptions=array()){
        $pages=Article::model()->getMenu(Option::SECTION_FOOTER_MENU_2);
        $menu=array();
        if(!$pages) return $menu;        
        return $this->menu($pages, $htmlOptions);
    }
    
    private function isMenuActive($route){
        return $this->route==$route;
    }
    
    private function isPageActive($url){
        return $url==implode('',array(Yii::app()->request->hostInfo, Yii::app()->request->url));
    }
    
    public function url($route, $params = array()) {
        //return Yii::app()->createUrl($route, $params);
        return Yii::app()->createAbsoluteUrl($route, $params);
    }

    public function render($view, $data = null, $return = false, $options = null) {
        $output = parent::render($view, $data, true);
        if(!YII_DEBUG){
            $compactor = Yii::app()->contentCompactor;
            if ($compactor == null)
                throw new CHttpException(500, Yii::t('messages', 'Missing component ContentCompactor in configuration.'));

            $output = $compactor->compact($output, $options);
        }
        if ($return)
            return $output;
        else
            echo $output;
    }

}